package com.book.web;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;

@WebServlet("/userborrow")
public class userborrow extends HttpServlet {

    @Override
    public void init() throws ServletException {
        try {
            Class.forName("com.mysql.cj.jdbc.Driver");
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req, resp);
    }
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        Connection conn = null;
        PreparedStatement ps = null;
        ResultSet rs = null;
        HttpSession session = req.getSession();
        String iduser = (String) session.getAttribute("iduser");
        try {
            conn = DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/library?serverTimezone=Asia/Shanghai&useUnicode=true&characterEncoding=utf8&useSSL=true","root","1234");
            ps = conn.prepareStatement("select * from book where borrow = " + iduser);
            rs = ps.executeQuery();
            List<Book> bookList = new ArrayList();
            while(rs.next()) {
                String borrow = rs.getString(7);
                Book book = new Book();
                if(borrow.equals(iduser)){
                        book.setId(rs.getString(1));
                        book.setName(rs.getString(2));
                        book.setAuthor(rs.getString(3));
                        book.setType(rs.getString(4));
                        book.setPhoto(rs.getString(5));
                        book.setContent(rs.getString(6));
                        book.setBorrow(rs.getString(7));
                        bookList.add(book);
                }
            }
            resp.setContentType("text/html");
            req.setAttribute("bookList", bookList);
            req.getRequestDispatcher("/userborrow.jsp").forward(req, resp);
            rs.close();
            conn.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }finally {
            try {
                if(rs != null){
                    rs.close();
                }
                if(ps!=null){
                    ps.close();
                }
                if(conn!=null){
                    conn.close();
                }
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }
}